package org.dxy.domain.handler.productionLine;

import com.google.common.eventbus.EventBus;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dxy.domain.port.IdGenerator;
import org.dxy.domain.port.CommandHandler;
import org.dxy.domain.port.repository.IProductionLineRepository;
import org.dxy.domain.command.productionLine.CreateProductionLineCommand;
import org.dxy.domain.model.aggregate.ProductionLine;
import org.dxy.types.common.CommandResult;
import org.springframework.stereotype.Component;

/**
 * @description: 创建产线命令处理器
 * @author: dxy
 * @createTime: 2025/6/26 10:30
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class CreateProductionLineCommandHandler implements CommandHandler<CreateProductionLineCommand, Long> {

    private final IProductionLineRepository productionLineRepository;
    private final EventBus eventBus;
    private final IdGenerator idGenerator;

    @Override
    public CommandResult<Long> handle(CreateProductionLineCommand command) {
        try {
            // 1. 生成设备 ID
            Long lineId = idGenerator.generate();

            ProductionLine productionLine = ProductionLine.create(command, lineId);
            productionLineRepository.save(productionLine);
            productionLine.getDomainEvents().forEach(eventBus::post);
            productionLine.clearDomainEvents();

            log.info("创建产线成功, lineId={}, command={}", lineId, command);
            return CommandResult.success(lineId, "创建产线成功");
        } catch (IllegalStateException e) {
            log.warn("创建产线失败，原因：{}", e.getMessage());
            return CommandResult.fail(null,e.getMessage());
        }
    }
}

